// Lindsay Gilmour
// Adam Lusch
// Dan Niceswanger
//
// Computer Graphics Project 1:
// Asteroids!
// A Tribute

#include "Ufo.h"

const float32 Ufo::MIN_SPEED = 5.0f;
const float32 Ufo::MAX_SPEED = 15.0f;

Ufo::Ufo(b2World* w, float32 x, float32 y)
	: Thing(w, 1, MAGIC_NUMBER)
{
	genLists();

	countdown = 0;
	
	b2BodyDef bodyDef;
	bodyDef.position.Set(x, y);
	body = world->CreateBody(&bodyDef);

	b2PolygonDef top;
	top.vertices[0] = b2Vec2(.5, .8);
	top.vertices[1] = b2Vec2(-.5, .8);
	top.vertices[2] = b2Vec2(-.5, .2);
	top.vertices[3] = b2Vec2(.5, .2);
	top.vertexCount = 4;
	top.density = 1.0f;
	top.friction = 0.0f;
	top.restitution = 0.995f;
	top.userData = this;
	body->CreateShape(&top);
	updateBoundingRadius(top);
	
	b2PolygonDef middle;
	middle.vertices[0] = b2Vec2(.7, .2);
	middle.vertices[1] = b2Vec2(-.7, .2);
	middle.vertices[2] = b2Vec2(-.7, 0);
	middle.vertices[3] = b2Vec2(.7, 0);
	middle.vertexCount = 4;
	middle.density = 1.0f;
	middle.friction = 0.0f;
	middle.restitution = 0.995f;
	middle.userData = this;
	body->CreateShape(&middle);
	updateBoundingRadius(middle);
	
	b2PolygonDef bottom;
	bottom.vertices[0] = b2Vec2(1.1, 0);
	bottom.vertices[1] = b2Vec2(-1.1, 0);
	bottom.vertices[2] = b2Vec2(-1.1, -.6);
	bottom.vertices[3] = b2Vec2(1.1, -.6);
	bottom.vertexCount = 4;
	bottom.density = 1.0f;
	bottom.friction = 0.0f;
	bottom.restitution = 0.995f;
	bottom.userData = this;
	body->CreateShape(&bottom);
	updateBoundingRadius(bottom);

	body->SetMassFromShapes();
}

Ufo::~Ufo()
{
}

void Ufo::genLists()
{
	// Main Ufo
	glNewList(baseDisplayList, GL_COMPILE);
	
	glLineWidth(1.5);
	
	//top
	glColor3f(.75, .75, .75);
	glBegin(GL_LINE_STRIP);
	glVertex2f(.5, .2);
	glVertex2f(.5, .6);
	glVertex2f(.3, .8);
	glVertex2f(-.3, .8);
	glVertex2f(-.5, .6);
	glVertex2f(-.5, .2);
	glEnd();

	//middle
	glColor3f(0.0, 1.0, 0.0);
	glBegin(GL_LINE_STRIP);
	glVertex2f(.7, 0);
	glVertex2f(.5, .2);
	glVertex2f(-.5, .2);
	glVertex2f(-.7, 0);
	glEnd();

	//bottom
	glBegin(GL_LINE_LOOP);
	glVertex2f(.9, 0);
	glVertex2f(-.9, 0);
	glVertex2f(-1.1, -.2);
	glVertex2f(-1.1, -.4);
	glVertex2f(-.9, -.6);
	glVertex2f(.9, -.6);
	glVertex2f(1.1, -.4);
	glVertex2f(1.1, -.2);
	glEnd();

	//"detail"
	glBegin(GL_LINES);
	glVertex2f(-.9, -.2);
	glVertex2f(.9, -.2);
	glVertex2f(-.9, -.4);
	glVertex2f(.9, -.4);
	glEnd();

	glEndList();
}

void Ufo::draw()
{
	if (countdown > 0)
	{
		--countdown;
	}
	else
	{
		float32 speed = b2Random(MIN_SPEED, MAX_SPEED);
		float32 angle = b2Random(0, 2 * M_PI);
		body->SetLinearVelocity(b2Vec2(speed * cos(angle), speed * sin(angle)));
		countdown = (int32)b2Random(MIN_TIME, MAX_TIME);
	}

	b2Vec2 position = body->GetPosition();
	float32 angle = body->GetAngle();

	glPushMatrix();
	glPushAttrib(GL_COLOR_BUFFER_BIT);
	
	glTranslatef(position.x, position.y, 0.0);
	glRotatef(angle*180.0/M_PI, 0.0, 0.0, 1.0);
	
	glTranslatef(0.05, 0.2, 0.0);
	
	glCallList(baseDisplayList);
	
	glPopAttrib();
	glPopMatrix();
}
